<template>
  <div class="page-container">
    <div class="q-search">
      <div
        :class="['q-item', queryParam.depositStatus == item.value ? 'active' : '', item.theme]"
        v-for="(item, index) in quickSearchs"
        :key="index"
        @click="depositStatusData(item)"
      >
        <div>{{ item.name }}</div>
        <div>{{ item.num }} 笔</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #ordermsg="{ record }">
        <div class="order-info-item">自有：{{ record.orderCode }}</div>
        <div class="order-info-item" v-if="record.channelOrderCode">渠道：{{ record.channelOrderCode }}</div>
        <div class="order-info-item" v-if="record.orderLabelList && record.orderLabelList.length > 0">
          <tag type="primary" style="margin-right: 8px" v-for="(item, index) in record.orderLabelList" :key="index">{{ item }}</tag>
        </div>
      </template>
      <!-- <template #depositType="{ record }">
      <div>{{ record.depositType == 1 ? '自驾长租押金' : '自驾短租押金' }}</div>
    </template> -->
      <template #carmsg="{ record }">
        <div>{{ record.carLicenseNo }}</div> <div>{{ record.carModelName }}</div>
      </template>
      <template #memberName="{ record }">
        <div>{{ record.memberName }}</div>
        <div>{{ record.memberPhone }}</div>
      </template>
      <template #time="{ record }"> {{ record.startTime }} - {{ record.endTime }} </template>
      <template #amount="{ record }">
        <div v-for="(item, index) in record.depositDtos" :key="index">
          <tag :type="tagTypeComputed(item.depositStatusName)" v-if="item.depositStatusName">{{ item.depositStatusName }}</tag>
          <span style="margin-left: 12px">{{ item.depositTypeName }}：</span>
          <span>{{ item.changeAmount ? item.changeAmount : '0' }}</span>
        </div>
      </template>
      <template #payTime="{ record }">
        <div>租车押金: {{ record.depositDtos.find((i) => i.depositType == 1).confirmTime || '-' }}</div>
        <div>违章押金: {{ record.depositDtos.find((i) => i.depositType == 2).confirmTime || '-' }}</div>
      </template>
      <template #planThawTime="{ record }">
        <div v-if="record.planThawTime">
          {{ dayjs(record.planThawTime).format('YYYY-MM-DD') }}
        </div>
        <div v-else>-</div>
      </template>
      <template #remarks="{ record }">
        <div>{{ record.depositDtos[0].remark || '-' }}</div>
      </template>
      <template #mout="{ record }">
        <div v-if="record.depositDtos[0].depositType == 1">租车押金抵扣: {{ record.depositDtos[0].deductionDepositAmount }}</div>
        <div v-if="record.depositDtos[1] && record.depositDtos[1].depositType == 2"
          >违章押金抵扣: {{ record.depositDtos[1].deductionDepositAmount }}</div
        >
        <div v-if="record.depositDtos[2] && record.depositDtos[2].depositType == 2"
          >违章押金抵扣: {{ record.depositDtos[2].deductionDepositAmount }}</div
        >
      </template>
      <template #confirmTime="{ record }">
        <div>租车押金: {{ record.depositDtos.find((i) => i.depositType == 1).confirmTime || '-' }}</div>
        <div>违章押金: {{ record.depositDtos.find((i) => i.depositType == 2).confirmTime || '-' }}</div>
      </template>
      <template #confirmUserName="{ record }">
        <div>租车押金: {{ record.depositDtos.find((i) => i.depositType == 1).confirmUserName || '-' }}</div>
        <div>违章押金: {{ record.depositDtos.find((i) => i.depositType == 2).confirmUserName || '-' }}</div>
      </template>
    </table-index>
  </div>
  <fee ref="feepage" @feepageConfirm="feepageConfirm" />
  <!-- 查看押金详情 -->
  <ZhimaDepositFreeModal ref="zhimaDepositFreeModalRef" :orderId="currentDeposit?.orderId" :showOperateBtn="true" />
  <!-- 押金扣款 -->
  <DeductionDeposit ref="DeductionDepositRef" @ok="loadData" />
  <!-- 免押码 -->
  <ListDepositModal ref="depositModalRef" @ok="loadData" />
  <!-- 全部解冻 -->
  <UnfreezeAll ref="unfreezeAllRef" @ok="loadData" />
  <!-- 转违章押金 -->
  <TransferDeposit ref="transferDepositRef" @ok="loadData" />
</template>

<script setup name="DepositList" lang="ts">
  import ZhimaDepositFreeModal from '../../order/short-order/components/alipay-deposit/zhima-deposit-free-modal.vue'
  import DeductionDeposit from '../../order/short-order/components/alipay-deposit/deduct-deposit.vue'
  import ListDepositModal from '../../order/short-order/components/alipay-deposit/list-deposit-modal.vue'
  import UnfreezeAll from '../../order/short-order/components/alipay-deposit/unfreeze-all.vue'
  import TransferDeposit from '../../order/short-order/components/alipay-deposit/transfer-deposit.vue'

  import fee from '@/views/confirmFee/deposit/index.vue'
  import { Message, Modal, Notification } from '@arco-design/web-vue'
  import { useExport } from '@/hooks/list'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getList, getNums, changeDeposit, depositExportExcel, checkViolation, checkDeposit } from '@/api/finance/deposit'
  import { onMounted, reactive, computed, ref } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'

  const route = useRoute()
  const DeductionDepositRef = ref()
  const depositModalRef = ref()
  const unfreezeAllRef = ref()
  const transferDepositRef = ref()
  const dict = usePageDict('depositOrderDict')
  const feepage = ref(null)
  const quickSearchs = ref([
    { value: 10, name: '应收未收', num: 0, theme: 'red' },
    { value: 30, name: '应收已收', num: 0, theme: 'blue' },
    { value: 50, name: '应退未退', num: 0, theme: 'red' },
    { value: 70, name: '应退已退', num: 0, theme: 'blue' },
  ])
  // dateTime Attrs
  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }
  // 接口参数（不包含page信息）
  const queryParam = reactive({})

  const tagTypeComputed = (statusStr) => {
    switch (statusStr) {
      case '应收未收':
        return 'warn'
      case '应收已收':
        return 'success'
      case '应退未退':
        return 'danger'
      case '应退已退':
        return 'primary'
      default:
        return 'default'
    }
  }

  // 导出事件
  const handleExport = () => {
    useExport(depositExportExcel, queryParam)
  }
  const depositStatusData = (item) => {
    queryParam.depositStatus = item.value
    loadData()
  }
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '订单号', prop: 'orderCodeChannelLike', placeholder: '请输入渠道/自有订单号', type: 'a-input' },
      { label: '承租人信息', prop: 'memberNameOrPhone', placeholder: '请输入承租人姓名/手机号', type: 'a-input' },
      { label: '车牌号', prop: 'carLicenseNoLike', type: 'a-input' },
      { label: '车型', prop: 'carModelId', type: 'remote-select', attrs: { type: 'car_model_saasList' } },
      { label: '订单状态', prop: 'orderStatusList', type: 'a-select', options: dict.orderStatusEnum, multiple: true },
      { label: '订单来源', prop: 'orderSource', type: 'a-select', options: dict.orderSourceEnum },
      { label: '订单标签', prop: 'orderLabels', type: 'a-select', options: dict.orderLabelEnum, multiple: true },
      { label: '押金门店', prop: 'siteId', type: 'remote-select', attrs: { type: 'site_listBystaff' } },
      { label: '还车门店', prop: 'returnSiteId', type: 'remote-select', attrs: { type: 'site_listBystaff' } },
      {
        label: '预计取车时间',
        prop: 'startTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.startTimeBegin = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '预计还车时间',
        prop: 'endTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.endTimeBegin = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
      {
        label: '实际取车时间',
        prop: 'actualStartTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualStartTimeBegin = value[0]
          queryParam.actualStartTimeEnd = value[1]
        },
      },
      {
        label: '实际还车时间',
        prop: 'actualEndTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualEndTimeBegin = value[0]
          queryParam.actualEndTimeEnd = value[1]
        },
      },
      {
        label: '下单时间',
        prop: 'orderCreateTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.orderCreateTimeBegin = value[0]
          queryParam.orderCreateTimeEnd = value[1]
        },
      },
      {
        label: '是否租车转违章押金',
        prop: 'carRentalChangeViolation',
        type: 'a-select',
        options: [
          { label: '是', value: 1 },
          { label: '否', value: 0 },
        ],
      },
      {
        label: '押金类型',
        prop: 'orderType',
        type: 'a-select',
        options: [
          { label: '自驾短租押金', value: 1 },
          { label: '自驾长租押金', value: 0 },
        ],
      },
      {
        label: '押金支付方式',
        prop: 'payTypeList',
        type: 'a-select',
        options: dict.payTypeEnum,
        multiple: true,
      },
      {
        label: '押金收取时间',
        prop: 'depositCollectTime',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.depositCollectTimeBegin = value[0]
          queryParam.depositCollectTimeEnd = value[1]
        },
      },
      {
        label: '租车押金状态',
        prop: 'carDepositStatusList',
        type: 'a-select',
        options: dict.depositStatusEnum,
        multiple: true,
      },
      {
        label: '违章押金状态',
        prop: 'illegalDepositStatusList',
        type: 'a-select',
        options: dict.depositStatusEnum,
        multiple: true,
      },
      {
        label: '押金预计解冻日期',
        prop: 'planThawTimeArr',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.planThawTimeBegin = value[0]
          queryParam.planThawTimeEnd = value[1]
        },
      },
    ]
  })

  // 初始化
  const init = () => {
    loadData()
  }
  const currentDeposit = ref()
  const zhimaDepositFreeModalRef = ref()
  // table 配置
  const table = useTable({
    columns: [
      { title: '押金类型', dataIndex: 'orderTypeName', width: 120, fixed: 'left' },
      { title: '订单信息', dataIndex: 'carMsg', width: 260, slotName: 'ordermsg' },
      { title: '车辆信息', dataIndex: 'siteName', width: 240, slotName: 'carmsg' },
      { title: '承租人', dataIndex: 'memberName', slotName: 'memberName', width: 120 },
      { title: '订单来源', dataIndex: 'channelTypeName', width: 100 },
      { title: '租赁周期', dataIndex: 'identityAuthStatusName', width: 360, slotName: 'time' },
      { title: '押金门店', dataIndex: 'siteName', width: 150 },
      { title: '订单状态', dataIndex: 'orderStatusName', width: 100 },
      { title: '押金', dataIndex: 'carDeposit', unit: '元', width: 240, slotName: 'amount' },
      { title: '押金支付方式', dataIndex: 'payTypeName', width: 120 },
      { title: '押金收取时间', dataIndex: 'payTime', width: 240, slotName: 'payTime' },
      { title: '押金预计解冻日期', dataIndex: 'planThawTime', width: 180, slotName: 'planThawTime' },
      { title: '押金备注', dataIndex: 'carDepositRemark', width: 240, slotName: 'remarks' },
      { title: '押金抵扣', dataIndex: 'carDeductionDepositAmount', unit: '元', width: 200, slotName: 'mout' },
      { title: '租车押金转违章押金', dataIndex: 'carRentalChangeViolationName', width: 180 },
      { title: '确认时间', dataIndex: 'confirmTime', slotName: 'confirmTime', width: 240 },
      { title: '确认人', dataIndex: 'confirmUserName', slotName: 'confirmUserName', width: 150 },
    ],
    operates: [
      {
        label: '详情',
        permission: 'svms:finance:deposit.detail',
        show: (record) => record.payType == 4,
        method: (record) => {
          console.log('详情 ', record)
          currentDeposit.value = record
          zhimaDepositFreeModalRef.value.show()
        },
      },
      {
        label: '免押码',
        permission: 'svms:finance:deposit.freeDepositCode',
        show: (record) => record.orderType == 1 && record.freeDepositCodeShow == 1,
        method: (record) => {
          console.log('免押码 ', record)
          depositModalRef.value.show({ ...record, id: record.orderId })
        },
      },
      {
        label: '押金扣款',
        permission: 'svms:finance:deposit.deduction',
        // 1 芝麻免押
        // 2 可用金额大于0
        show: (record) => record.payType == 4 && record.availableDepositAmount > 0,
        method: (record) => {
          checkDeposit({ id: record.orderId }).then((res) => {
            const { errorCode } = res.result
            if (errorCode == 200) {
              // 传入订单id
              DeductionDepositRef.value.show(record.orderId)
            } else if (errorCode == 888) {
              Message.error('押金已不支持押金扣款')
            } else if (errorCode == 999) {
              Message.error('存在请求中的数据，暂不支持押金扣款')
            }
          })
        },
      },
      // 租车押金 carDepositStatus      10:应收未收，30:应收已收，50:应退未退，70:应退已退
      // 违章押金 illegalDepositStatus  10:应收未收，30:应收已收，50:应退未退，70:应退已退
      {
        label: '收租车押金',
        permission: 'svms:finance:deposit.getrental',
        show: (record) => record.payType != 4 && record.carDepositStatus == 10,
        method: (record) => {
          if (record.orderType == 1) {
            checkDeposit({ id: record.orderId, type: 2 }).then((res) => {
              const { errorCode } = res.result
              if (errorCode == 200) {
                click(record, 1)
              } else if (errorCode == 888) {
                Message.error('押金已不支持手动收租车押金')
              } else if (errorCode == 999) {
                Message.error('存在请求中的数据，暂不支持收租车押金')
              }
            })
          } else {
            click(record, 1)
          }
        },
      },
      {
        label: '收违章押金',
        permission: 'svms:finance:deposit.getviolation',
        show: (record) => record.payType != 4 && record.illegalDepositStatus == 10,
        method: (record) => {
          if (record.orderType == 1) {
            checkDeposit({ id: record.orderId, type: 3 }).then((res) => {
              const { errorCode } = res.result
              if (errorCode == 200) {
                click(record, 2)
              } else if (errorCode == 888) {
                Message.error('押金已不支持手动收违章押金')
              } else if (errorCode == 999) {
                Message.error('存在请求中的数据，暂不支持收违章押金')
              }
            })
          } else {
            click(record, 2)
          }
        },
      },
      {
        label: '退租车押金',
        permission: 'svms:finance:deposit.outrental',
        show: (record) => record.payType != 4 && record.carDepositStatus == 50,
        method: (record) => {
          click(record, 3)
        },
      },
      {
        label: '退违章押金',
        permission: 'svms:finance:deposit.outviolation',
        show: (record) => record.payType != 4 && record.illegalDepositStatus == 50,
        method: (record) => {
          click(record, 4)
        },
      },
      {
        label: '租车转违章',
        permission: 'svms:finance:deposit.rentaltoviolation',
        show: (record) =>
          record.payType != 4 && record.orderStatus == 300 && record.carDepositStatus == 50 && record.illegalDepositStatus == 10,
        method: (record) => {
          click(record, 5)
        },
      },
      {
        label: '租车转违章',
        permission: 'svms:finance:deposit.rentaltoviolation',
        // 1 芝麻免押
        // 2 未操作过租车转违章
        // 3 租车押金应收已收或应退未退
        show: (record) =>
          record.orderType == 1 &&
          record.payType == 4 &&
          record.carRentalChangeViolation == 0 &&
          [30, 50].includes(record.carDepositStatus),
        method: (record) => {
          checkDeposit({ id: record.orderId, type: 1 }).then((res) => {
            const { errorCode, currentlyAvailableDepositAmount, receivedDepositAmount, violationFreezeDay } = res.result
            let carChangeViPlanThawTime = res.result.carChangeViPlanThawTime
            if (carChangeViPlanThawTime) {
              carChangeViPlanThawTime = dayjs(carChangeViPlanThawTime).format('YYYY-MM-DD')
            }
            if (errorCode == 200) {
              transferDepositRef.value.show({
                // 租车押金id
                carDepositId: record.carDepositId,
                availableDepositAmount: currentlyAvailableDepositAmount,
                illegalDepositAmount: receivedDepositAmount,
                freezeDay: violationFreezeDay,
                carChangeViPlanThawTime: carChangeViPlanThawTime,
              })
            } else if (errorCode == 888) {
              Message.error('押金已不支持租车转违章')
            } else if (errorCode == 999) {
              Message.error('存在请求中的数据，暂不支持租车转违章')
            }
          })
        },
      },
      {
        label: '全部解冻',
        permission: 'svms:finance:deposit.allthaw',
        // 1 芝麻免押
        // 2 可用金额大于0
        show: (record) => record.payType == 4 && record.availableDepositAmount > 0,
        method: (record) => {
          checkDeposit({ id: record.orderId }).then((res) => {
            const { errorCode, currentlyAvailableDepositAmount } = res.result
            if (errorCode == 200) {
              unfreezeAllRef.value.show({
                ...record,
                availableDepositAmount: currentlyAvailableDepositAmount,
              })
            } else if (errorCode == 888) {
              Message.error('押金已不支持全部解冻')
            } else if (errorCode == 999) {
              Message.error('存在请求中的数据，暂不支持全部解冻')
            }
          })
        },
      },
    ],
    buttons: [
      {
        mode: 'import',
        label: '导出',
        permission: 'svms:finance:deposit.export',
        method: () => handleExport(),
      },
    ],
  })
  const click = (record, type) => {
    if (type == 1) {
      // 收租车押金
      handleBeforeOk(record.carDepositId)
    }
    if (type == 2) {
      // 收违章押金
      handleBeforeOk(record.illegalDepositId)
    }
    if (type == 3) {
      // 退租车押金
      handleBeforeOk(record.carDepositId)
    }
    if (type == 4) {
      // 退违章押金 (接口验证弹窗)
      checkViolation({ id: record.illegalDepositId }).then((res) => {
        // 2024-06-03 广腾要求改为false
        if (res.result == false) {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '当前订单有违章未确认，请确认是否退违章押金',
            onOk: () => {
              handleBeforeOk(record.illegalDepositId)
            },
          })
        } else {
          handleBeforeOk(record.illegalDepositId)
        }
      })
    }
    if (type == 5) {
      // 租车转违章 (弹窗)
      Modal.confirm({
        title: '租车转违章',
        simple: true,
        cancelText: '取消',
        okText: '确认',
        bodyStyle: {
          'text-align': 'center',
        },
        content: '确认将租车押金费转成违章押金？',
        onOk: () => {
          // 调用租车转违章接口
          changeDeposit({ id: record.carDepositId }).then(() => {
            Notification.success({
              content: '操作成功',
              closable: true,
              duration: 3000,
            })
            loadData()
          })
        },
      })
    }
  }
  // 退违章押金弹窗确认
  const handleBeforeOk = (depositId) => {
    feepage.value.show(depositId)
  }

  const getnum = () => {
    getNums().then((res) => {
      quickSearchs.value[0].num = res.result.notReceivedCount
      quickSearchs.value[1].num = res.result.receivedCount
      quickSearchs.value[2].num = res.result.wantDrawbackCount
      quickSearchs.value[3].num = res.result.finishDrawbackCount
    })
  }

  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getList)

  defineExpose({
    loadData,
  })
  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    init()
    getnum()
  }
  onMounted(async () => {
    // 违章押金或者租车押金即将到期
    let { status = '', time = '', statusList = '' } = route.query
    status && (queryParam[status] = statusList.split(',').map(Number))
    if (time) {
      let startTime = dayjs().format('YYYY-MM-DD')
      let endTime = dayjs().add(Number(time), 'day').format('YYYY-MM-DD')
      queryParam.planThawTimeArr = [startTime, endTime]
      queryParam.planThawTimeBegin = startTime
      queryParam.planThawTimeEnd = endTime
    }
    init()
    getnum()
  })
</script>

<style lang="less" scoped>
  .q-search {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
    .q-item {
      width: 25%;
      display: flex;
      flex-direction: column;
      height: 62px;
      font-weight: 400;
      color: #ffffff;
      border-radius: 2px 2px 2px 2px;
      padding: 9px 16px;
      cursor: pointer;

      &.red {
        background-color: rgba(247, 105, 100, 1);
      }

      &.blue {
        background-color: rgba(149, 180, 252, 1);
      }

      div:nth-child(1) {
        font-size: 10px;
      }
      div:nth-child(2) {
        font-size: 20px;
        font-weight: 600;
      }

      &:hover {
        transform: scale(1.1);
        transition: transform 0.3s;
      }
    }
    .q-item:nth-of-type(n + 2) {
      margin-left: 20px;
    }
    .active {
      box-shadow: 0 4px 5px rgb(5 19 56 / 20%);
      &.red {
        border-bottom: 6px solid #e23838;
      }
      &.blue {
        border-bottom: 6px solid #5786f3;
      }
    }
  }
  .penal {
    height: 260px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }
</style>
